package org.one.stone.soup.grfxML.plugin.system;

import java.io.File;

import org.one.stone.soup.file.FileChangeListener;
import org.one.stone.soup.file.FileWatch;
import org.one.stone.soup.grfxML.DataPlugin;
import org.one.stone.soup.grfxML.DataSize;
import org.one.stone.soup.grfxML.DataState;
import org.one.stone.soup.grfxML.DataString;
import org.one.stone.soup.grfxML.GrfxMLEngine;
import org.one.stone.soup.grfxML.plugin.SimplePlugin;
import org.one.stone.soup.grfxML.plugin.grfxMLCaster;
import org.one.stone.soup.mjdb.data.field.Field;
import org.one.stone.soup.mjdb.data.field.LockException;

public class FileWatcher extends SimplePlugin implements FileChangeListener {
	DataString file = new DataString();
	DataSize refreshTime = new DataSize();
	DataState changed = new DataState();

	FileWatch watcher;
	boolean hasChanged=false;
/**
 * FileToText constructor comment.
 */
public FileWatcher(GrfxMLEngine engine) {
	super(engine);
}
/**
 * fileChanged method comment.
 */
public void fileChanged(File file)
{
	hasChanged = true;
}
/**
 * getClone method comment.
 */
public DataPlugin getClone() {
	return null;
}
/**
 * getClone method comment.
 */
public DataPlugin getClone(String path) {
	return null;
}
/**
 * initialize method comment.
 */
public void initialize()
{
	watcher = new FileWatch( file.getValue(),refreshTime.getValue() );
	watcher.addListener( this );    
}
/**
 * process method comment.
 */
public void process()
{
 try{

	if( file.hasChanged() && file.getValue().length()>0 )
	{
		watcher = new FileWatch( file.getValue(),refreshTime.getValue() );
		watcher.addListener( this );
	}

	if(changed.getValue()==true)
	{
		changed.setValue( false,this );
	}

	if(hasChanged==true)
	{
		hasChanged=false;
		changed.setValue( true,this );
	}

 }catch(LockException le)
 {}
}
/**
 * register method comment.
 */
public void register(org.one.stone.soup.mjdb.data.field.DataLinker store)
{
	file = grfxMLCaster.cast(file,getArg(file,0,store));
	changed = grfxMLCaster.cast(changed,getArg(changed,1,store));
	refreshTime = grfxMLCaster.cast(refreshTime,getArg(refreshTime,2,store));
}
public void replace(Field oldObj, Field newObj)
{
	file = grfxMLCaster.replace(file,oldObj,newObj);
	refreshTime = grfxMLCaster.replace(refreshTime,oldObj,newObj);
	changed = grfxMLCaster.replace(changed,oldObj,newObj);
}
/**
 * stop method comment.
 */
public void stop()
{
    watcher.removeAllListeners();
    watcher.stop();
    watcher=null;
}

}
